package cn.shengchao.examstar.me.course.acl.adapters.repositories;

import cn.shengchao.examstar.me.course.acl.ports.repositories.IContactUserCourseRepository;
import cn.shengchao.examstar.me.course.domain.ContactUserCourseKnowledge;
import cn.shengchao.examstar.me.infrastructure.dao.ProductCourseUserDao;
import cn.shengchao.examstar.me.infrastructure.dao.po.TProductCourseUser;
import cn.shengchao.examstar.me.play.domain.OnlineUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import top.continew.starter.cache.redisson.util.RedisUtils;

import java.util.List;

import static cn.shengchao.base.constant.Constants.RedisKey.COURSE_PROGRESS_LOG_KEY;

/**
 * @program: examstarapi
 * @description: 用户课程统计
 * @author: Xiong weiqiang
 * @create: 2025-04-19 17:35
 */
@Repository
public class ContactUserCourseRepository implements IContactUserCourseRepository {
    @Autowired
    private ProductCourseUserDao productCourseUserDao;
    @Override
    public List<ContactUserCourseKnowledge> getMyCourseKnowledgeList(Long studentId, Long courseId) {
        return productCourseUserDao.selectList(new LambdaQueryWrapper<TProductCourseUser>()
                .eq(TProductCourseUser::getStudentId, studentId)
                .eq(TProductCourseUser::getDeleted, 0)
                .eq(courseId != -1, TProductCourseUser::getCourseId, courseId)).stream().map(item -> {
            OnlineUser onlineUser = RedisUtils.get(COURSE_PROGRESS_LOG_KEY.formatted(studentId, item
                    .getKnowledgeNodeId()));
            ContactUserCourseKnowledge myCourse = new ContactUserCourseKnowledge();
            myCourse.setCourseId(item.getCourseId());
            myCourse.setKnowledgeNodeId(item.getKnowledgeNodeId());
            myCourse.setStudentId(item.getStudentId());
            myCourse.setLastPlayTime(item.getLastPlayTime());
            myCourse.setPlayProgress(Math.toIntExact(onlineUser != null
                    ? onlineUser.getProgress()
                    : item.getLastPlayProgress()));
            myCourse.setUnlockTime(item.getUnlockTime());
            myCourse.setUnlockType(item.getUnlockType());
            myCourse.setPayId(item.getPayId());
            myCourse.setWatchProgress(item.getWatchProgress());
            myCourse.setWatchLength(item.getWatchLength());
            return myCourse;
        }).toList();
    }
}